package com.ym.jiujiangeyou.bitmap;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
import com.ym.jiujiangeyou.util.FileManager;

/**
 * @author 叶铭
 * @email yeming_1001@163.com
 * @version V1.0
 * @Description: 简单下载图片工具类(单张)
 */
public class SimpleImageLoad {

	private ExecutorService executorService;
	private int requestWidth,requestHeight ;

	public SimpleImageLoad(Context context) {
		executorService = Executors.newFixedThreadPool(1);
	}
	
	/** 
	* @param widthSize
	* @param heightSize  
	* @retur  void 
	* @Description: set Size 
	*/
	public void setSize(int widthSize,int heightSize){
		this.requestHeight = widthSize ;
		this.requestHeight = heightSize ;
	}

	/**
	 * @param url
	 * @param imageView
	 * @retur void
	 * @Description: 提供调用
	 */
	public void DisplayImage(String url, ImageView imageView) {
		if (url == null || url.length() < 1 || imageView == null) {
			return;
		}
		queueImage(url, imageView);
	}

	/**
	 * @param url
	 * @param imageView
	 * @retur void
	 * @Description: 下载
	 */
	private void queueImage(String url, ImageView imageView) {
		ImageLoad p = new ImageLoad(url, imageView);
		executorService.submit(new Loader(p));
	}

	private Bitmap getBitmap(String url) {
		File f = FileManager.getFile(url);
		// 从sd找
		Bitmap b = null;
		if (f != null && f.exists()) {
			b = decodeFile(f);
		/*//	b = BitmapUtil.zoomImage(FileManager.getBitmap(url), requestWidth,requestHeight) ;
			try {
				b = BitmapFactory.decodeStream(new FileInputStream(f)) ;
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				b = null ;
			}*/
		}
		if (b != null) {
			return b;
		}
		// 最后从指定的url中下载图片
		try {
			Bitmap bitmap = null;
			URL imageUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) imageUrl
					.openConnection();
			conn.setConnectTimeout(30000);
			conn.setReadTimeout(30000);
			conn.setInstanceFollowRedirects(true);
			InputStream is = conn.getInputStream();
			OutputStream os = new FileOutputStream(f);
			CopyStream(is, os);
			os.close();
			//bitmap = BitmapFactory.decodeStream(new FileInputStream(f)) ;
			bitmap = decodeFile(f);
		//	bitmap = BitmapUtil.zoomImage(FileManager.getBitmap(url), requestWidth,requestHeight) ;
			return bitmap;
		} catch (Exception ex) {
			Log.e("",
					"getBitmap catch Exception...\nmessage = "
							+ ex.getMessage());
			return null;
		}
	}

	// 按比例缩放
	private Bitmap decodeFile(File f) {
		try {
			// decode image size
			BitmapFactory.Options o = new BitmapFactory.Options();
			o.inJustDecodeBounds = true;
			BitmapFactory.decodeStream(new FileInputStream(f), null, o);
			// Find the correct scale value. It should be the power of 2.
			final int REQUIRED_SIZE = 360;
			int width_tmp = o.outWidth, height_tmp = o.outHeight;
			Log.e("", "w = " + width_tmp + ", h = " + height_tmp);
			int scale = 1;
			while (true) {
				if (width_tmp / 2 < REQUIRED_SIZE
						|| height_tmp / 2 < REQUIRED_SIZE)
					break;
				width_tmp /= 2;
				height_tmp /= 2;
				scale *= 2;
			}
			// decode with inSampleSize
			BitmapFactory.Options o2 = new BitmapFactory.Options();
			o2.inSampleSize = scale;
			return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
		} catch (FileNotFoundException e) {
		}
		return null;
	}

	
		private class ImageLoad {
			public String url;
			public ImageView imageView;

			public ImageLoad(String u, ImageView i) {
				url = u;
				imageView = i;
			}
		}

	class Loader implements Runnable {
		ImageLoad imageLoad;

		Loader(ImageLoad imageLoad) {
			this.imageLoad = imageLoad;
		}

		@Override
		public void run() {
			Bitmap bmp = getBitmap(imageLoad.url);
			BitmapDisplayer bd = new BitmapDisplayer(bmp, imageLoad);
			// 更新的操作放在UI线程中
			Activity a = (Activity) imageLoad.imageView.getContext();
			a.runOnUiThread(bd);
		}
	}

	// 用于在UI线程中更新界面
	class BitmapDisplayer implements Runnable {
		Bitmap bitmap;
		ImageLoad photoToLoad;

		public BitmapDisplayer(Bitmap b, ImageLoad p) {
			bitmap = b;
			photoToLoad = p;
		}

		public void run() {
			if (bitmap != null)
				photoToLoad.imageView.setImageBitmap(bitmap);

		}
	}

	public static void CopyStream(InputStream is, OutputStream os) {
		final int buffer_size = 1024;
		try {
			byte[] bytes = new byte[buffer_size];
			for (;;) {
				int count = is.read(bytes, 0, buffer_size);
				if (count == -1)
					break;
				os.write(bytes, 0, count);
			}
		} catch (Exception ex) {
			Log.e("", "CopyStream catch Exception...");
		}
	}
}
